<template>
  <el-card class="panel-card">
    <template #header>
      <div class="card-header">
        <el-text class="mr5">{{ $t('message.random.selectCharacter') }}</el-text>
        <el-select-v2
          v-model="selectedCharacters"
          :options="characterOptions"
          :item-height="50"
          :height="350"
          :props="{ value: 'name', label: 'cn_name' }"
          multiple
          clearable
          filterable
          :placeholder="$t('message.random.selectCharacter')"
          class="full-width-select"
          collapse-tags
          collapse-tags-tooltip
          :max-collapse-tags="3"
          size="large"
        >
        <template #default="{ item }">

          <div class="suggestion-content">
            <el-avatar
              :src="getCharacterImageUrl(item.name)"
              size="default"
              class="avatar"
              @error="handleImageError"
            >
              <template #default>
                <el-icon><User /></el-icon>
              </template>
            </el-avatar>
            <div class="info">
              <span class="value">{{ item.name }}</span>
              <span class="label">{{ item.cn_name }}</span>
            </div>
          </div>
        </template>
      </el-select-v2>
      </div>
    </template>

    <div class="character-thumbnails">
      <el-popover
        v-for="(character, index) in selectedCharacterObjects"
        :key="index"
        placement="top"
        trigger="click"
        :width="400"
      >
        <template #reference>
          <el-image :src="getCharacterImageUrl(character.name)" style="width: 100px; margin-left: 5px" fit="contain" />
        </template>
        <el-row>
          <el-rate v-model="character.rating" show-score :max="10" allow-half clearable score-template="{value} points" />
        </el-row>
        <el-row>
          <div style="display: flex;">
            <el-text>{{ character.name }}</el-text>
            <el-button type="primary" size="default" class="ml10" @click="handleUpdateCharacter(character)">
              {{ $t('message.common.submit') }}
            </el-button>
          </div>
        </el-row>
      </el-popover>
      <div v-if="selectedCharacters.length === 0" class="placeholder">
        <el-icon><Picture /></el-icon>
        <span>{{ $t('message.random.noCharacterSelected') }}</span>
      </div>
    </div>
    <div>
      <el-button class="ml10" size="default" type="primary" @click="getRandomCharacter()" icon="MagicStick">
        {{ $t('message.random.randomCharacter') }}
      </el-button>
      <el-button size="default" type="primary" @click="getRandomCharacterByOne()" icon="MagicStick">
        {{ $t('message.random.randomOneCharacter') }}
      </el-button>
      <el-popover placement="top" :width="470" trigger="hover">
        <template #reference>
          <el-button size="default" class="range-btn" type="primary">{{ characterRate }}</el-button>
        </template>
        <div>
          <el-slider
            style="width:400px;margin-left: 20px;"
            :step="0.5"
            v-model="characterRate"
            range
            show-stops
            :min="0"
            :max="10"
          />
        </div>
      </el-popover>
      <el-button size="default" type="primary" icon="ele-ArrowLeft" @click="handlePrevCharacter"></el-button>
      <el-button size="default" type="primary" icon="ele-ArrowRight"  @click="handleNextCharacter"></el-button>
    </div>
  </el-card>
</template>

<script lang="ts" setup>
import { ref, computed, onMounted, watch } from 'vue';
import { commonApi } from '@renderer/api/common';
import { useConfigStore } from '@renderer/stores/configStore';
import { useExPrompt } from '@renderer/stores/useExPrompt';
import { ElMessage } from 'element-plus';

interface Character {
  name: string;
  cn_name: string;
  tag: string;
  rating: number;
}

const configStore = useConfigStore();
const exPromptStore = useExPrompt();

const selectedCharacters = ref<string[]>([]);
const characterOptions = ref<Character[]>([]);
const characterRate = ref([0, 0]);

const selectedCharacterObjects = computed(() => {
  return selectedCharacters.value.map(name => {
    return characterOptions.value.find(c => c.name === name) || { name, cn_name: name, tag: '', rating: 0 };
  });
});

const getCharacterImageUrl = (name: string) => {
  if (!name) return '';
  return configStore.comfyProxyImage(`file://${configStore.config.imagesPath}\\character\\${name}.webp`);
};

const handleImageError = (event: Event) => {
  const img = event.target as HTMLImageElement;
  if (img) {
    img.style.display = 'none';
  }
};

const handleUpdateCharacter = (character: Character) => {
  commonApi().updateCharacter({ name: character.name, rating: character.rating }).then(res => {
    ElMessage.success(JSON.stringify(res.data));
  }).catch(() => {
    ElMessage.error("更新角色评分失败");
  });
};

const getCharacterOptionList = () => {
  commonApi().getCharacterList().then(res => {
    characterOptions.value = res.data.data;
  });
};

const getRandomCharacter = () => {
  commonApi().getRandomCharacter({ rating: characterRate.value })
    .then(res => {
      const newCharacter = res.data.result;
      if(newCharacter && newCharacter.name){
        const existingIndex = characterOptions.value.findIndex(c => c.name === newCharacter.name);
        if (existingIndex === -1) {
          characterOptions.value.push(newCharacter);
        }
        if (!selectedCharacters.value.includes(newCharacter.name)) {
          selectedCharacters.value.push(newCharacter.name);
        }
      }
    });
};

const getRandomCharacterByOne = async () => {
  const wasEmpty = selectedCharacters.value.length === 0;
  if (!wasEmpty) {
    selectedCharacters.value = [];
    await new Promise(resolve => setTimeout(resolve, 50));
  }
  try {
    const res = await commonApi().getRandomCharacter({ rating: characterRate.value });
    const newCharacter = res.data.result;
    const existingIndex = characterOptions.value.findIndex(c => c.name === newCharacter.name);
    if (existingIndex === -1) {
      characterOptions.value.push(newCharacter);
    }
    selectedCharacters.value = [newCharacter.name];
  } catch (error) {
    ElMessage.error('获取角色失败');
    if (!wasEmpty) {
      selectedCharacters.value = [];
    }
  }
};

const getAdjacentCharacter = async (params: any) => {
  try {
    const response = await commonApi().getAdjacentCharacter(params);
    if (!response.data.result) {
      ElMessage.error('未找到相邻人物记录');
      return null;
    }
    return response.data.result as Character;
  } catch (error) {
    ElMessage.error('获取相邻人物记录时出错:' + JSON.stringify(error));
    return null;
  }
};

const handlePrevCharacter = async () => {
  let currentName = '';
  if (selectedCharacters.value.length === 1) {
    currentName = selectedCharacters.value[0];
  }
  const newCharacter = await getAdjacentCharacter({
    current_name: currentName,
    direction: 'prev',
    rating: characterRate.value
  });

  if (newCharacter) {
    const existingIndex = characterOptions.value.findIndex(c => c.name === newCharacter.name);
    if (existingIndex === -1) {
      characterOptions.value.push(newCharacter);
    }
    selectedCharacters.value = [newCharacter.name];
  }
};

const handleNextCharacter = async () => {
  let currentName = '';
  if (selectedCharacters.value.length === 1) {
    currentName = selectedCharacters.value[0];
  }
  const newCharacter = await getAdjacentCharacter({
    current_name: currentName,
    direction: 'next',
    rating: characterRate.value
  });
  if (newCharacter) {
    const existingIndex = characterOptions.value.findIndex(c => c.name === newCharacter.name);
    if (existingIndex === -1) {
      characterOptions.value.push(newCharacter);
    }
    selectedCharacters.value = [newCharacter.name];
  }
};

watch(
  selectedCharacters,
  (newCharacterNames) => {
    if (newCharacterNames.length > 0) {
      const tags = newCharacterNames
        .map(name => {
          const character = characterOptions.value.find(c => c.name === name);
          return character ? character.tag : null;
        })
        .filter(tag => tag)
        .join(',');
      exPromptStore.setCharacterTag(tags);
    } else {
      exPromptStore.setCharacterTag('');
    }
  },
  { deep: true }
);

onMounted(() => {
  getCharacterOptionList();
});
</script>

<style lang="scss" scoped>
.panel-card {
    border-radius: 12px;
    box-shadow: var(--el-box-shadow-light);

    :deep(.el-card__header) {
      background: linear-gradient(145deg, var(--el-fill-color-lighter), var(--el-fill-color));
      border-bottom: none;
      padding: 16px 20px;
    }

    .card-header {
      display: flex;

      .el-text {
        white-space: nowrap;
        color: var(--el-text-color-primary);
        font-size: 16px;
      }
    }
  }

.character-thumbnails {
  min-height: 120px;
  display: flex;
  flex-wrap: wrap;
  gap: 5px;
  position: relative;
  padding: 5px;
  border: 1px dashed var(--el-border-color);
  border-radius: 4px;
  margin-bottom: 10px;
  transition: all 0.3s ease;
  background-color: var(--el-fill-color-lighter);

  .el-image {
    width: 100px;
    height: 100px;
    border: 1px solid var(--el-border-color-lighter);
    border-radius: 4px;
    background: var(--el-fill-color-blank);
    overflow: hidden;
  }

  .placeholder {
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    color: var(--el-text-color-placeholder);
    font-size: 14px;
    pointer-events: none;

    .el-icon {
      font-size: 30px;
      margin-bottom: 5px;
    }
  }
}

.range-btn{
  min-width: 70px;
}

.suggestion-content {
  display: flex;
  width: 100%;
  min-width: 200px;
}

.avatar {
  margin-right: 12px;
  flex-shrink: 0;
}

.info {
  display: flex;
  gap: 15px;
  overflow: hidden;
}

.value {
  font-weight: 600;
  margin-bottom: 2px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.label {
  font-size: 0.85em;
  color: var(--el-text-color-secondary);
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
